import time

import requests
from requests_html import HTMLSession

from common.request import requestutil
from common.request.extract import *
from common.utils import timeutil


class searcher_tianyancha():
    domain = "https://www.tianyancha.com"
    headers = requestutil.get_default_header({'Host': 'www.tianyancha.com', 'Referer': domain})

    def __init__(self, cookies):
        if cookies:
            self.cookies = cookies
            self.session = HTMLSession()
            self.session.cookies.update(cookies)
            # self.session.get(self.domain, headers=self.headers, cookies=self.cookies)
        else:
            raise Exception("cookie参数不能为空")

    def get_session(self):
        return self.session

    def search_list(self, orgname):
        url = self.domain + '/search?key=' + orgname
        resp = requestutil.get(url, timeout=10, keep_session=self.get_session())
        print("是否包含_gat_gtag_UA_123487620_1:" + str(resp.text.find("gat_gtag_UA_123487620") > 0))
        # 验证查询页面是否正确加载
        if not (resp.text.find("为你找到") > 0 and resp.text.find("家公司") > 0):
            if resp.text.find("抱歉，没有找到相关企业") > 0:
                return []
            elif resp.text.find("收不到验证码？试试语音验证") > 0:
                print("登录失效,请浏览器重新登录并推送cookie!!账号:" + self.cookies["current_user"])
                raise Exception("登录失效,请浏览器重新登录并推送cookie!!账号:" + self.cookies["current_user"])
            elif resp.text.find("<center>❤</center>") > 0:
                print("请求需要验证码!!账号:" + self.cookies["current_user"])
                raise Exception("请求需要验证码!!账号:" + self.cookies["current_user"])
            else:
                print("没有正确加载页面,请更换词条查询试试!!" + url)
                print(resp.text)
                raise Exception("没有正确加载页面,请更换词条查询试试!!")
        items = resp.html.find(
            ".sv-search-container .sv-search-company")
        results = []
        index = 0
        for item in items:
            index += 1

            result = {}
            result["i"] = index
            result["KEYWORD"] = orgname
            title_item = item.find("div.content > div.header > a")[0]
            result["STANDED_NAME"] = title_item.text

            result["TELEPHONE"] = first_node_text(item, "span:nth-child(3) > span:nth-child(1)")

            result["EMAIL"] = first_node_text(item,
                                              "div.content > div.contact.row > div:nth-child(2) > span:nth-child(2)")

            result["FDDBR"] = first_node_text(item,
                                              "div.content > div.info.row.text-ellipsis > div:nth-child(1) > a")
            result["ZCZB"] = first_node_text(item,
                                             "div.content > div.info.row.text-ellipsis > div:nth-child(2) > span")
            result["PROVINCE"] = first_node_text(item, ".site")
            result["ADDRESS"] = result["PROVINCE"]

            results.append(result)
        results.sort(key=lambda x: x["i"], reverse=False)
        return results


if __name__ == "__main__":

    cookies = requestutil.cookie_dict_from_str(
        "aliyungf_tc=AQAAABAJ32TLPQ4A9k33dMk4fhS8G1Bm; ssuid=4220356200; csrfToken=pcenZMQMg1ISp7BnnS0HkAx7; TYCID=e9a5a90092fd11e9bdfb51a17a08499c; undefined=e9a5a90092fd11e9bdfb51a17a08499c; jsid=SEM-BAIDU-PP-VI-001065; tyc-user-info=%257B%2522claimEditPoint%2522%253A%25220%2522%252C%2522myAnswerCount%2522%253A%25220%2522%252C%2522myQuestionCount%2522%253A%25220%2522%252C%2522signUp%2522%253A%25220%2522%252C%2522explainPoint%2522%253A%25220%2522%252C%2522privateMessagePointWeb%2522%253A%25220%2522%252C%2522nickname%2522%253A%2522%25E6%2589%25B6%25E8%258B%258F%2522%252C%2522integrity%2522%253A%25220%2525%2522%252C%2522privateMessagePoint%2522%253A%25220%2522%252C%2522state%2522%253A0%252C%2522announcementPoint%2522%253A%25220%2522%252C%2522isClaim%2522%253A%25220%2522%252C%2522vipManager%2522%253A%25220%2522%252C%2522discussCommendCount%2522%253A%25220%2522%252C%2522monitorUnreadCount%2522%253A%25220%2522%252C%2522onum%2522%253A%25220%2522%252C%2522claimPoint%2522%253A%25220%2522%252C%2522token%2522%253A%2522eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxMzkxNjg2ODY0OSIsImlhdCI6MTU2MDk5NjcyNywiZXhwIjoxNTkyNTMyNzI3fQ.tX3F8d4-r5SeGuONW9WVJK4zUshZSaYWkBYHvRWa3Fjqi6A3Moi6YmfsM89F5e8LaV7fj8w5413QJcQGDoTRCQ%2522%252C%2522pleaseAnswerCount%2522%253A%25220%2522%252C%2522redPoint%2522%253A%25220%2522%252C%2522bizCardUnread%2522%253A%25220%2522%252C%2522vnum%2522%253A%25220%2522%252C%2522mobile%2522%253A%252213916868649%2522%257D; auth_token=eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxMzkxNjg2ODY0OSIsImlhdCI6MTU2MDk5NjcyNywiZXhwIjoxNTkyNTMyNzI3fQ.tX3F8d4-r5SeGuONW9WVJK4zUshZSaYWkBYHvRWa3Fjqi6A3Moi6YmfsM89F5e8LaV7fj8w5413QJcQGDoTRCQ; bannerFlag=undefined; Hm_lvt_e92c8d65d92d534b0fc290df538b4758=1560836752,1560995484,1560999149,1561094271; Hm_lpvt_e92c8d65d92d534b0fc290df538b4758=1561094271; _ga=GA1.2.893090315.1560995484; _gid=GA1.2.2118363815.1560995484; _gat_gtag_UA_123487620_1=1")

    cookies["current_user"] = "test_user"
    print(cookies)
    s = searcher_tianyancha(cookies)
    for i in range(0, 200):
        try:
            print(str(i) + "--正常" + str(s.search_list("四川广运九州通医药有限公司")))
        except Exception as e:
            print(str(i) + "--异常" + str(e))
            break
        time.sleep(9)
